<template>
  <div class="authority">
    <div class="gva-search-box">
      <el-form ref="searchForm" :inline="true">
        <el-form-item label="行政区划">
          <el-cascader style="width: 100%" :options="areaList" :props="props2" v-model="searchPids"
            @change="searchAreaChange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">
            查询
          </el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box unit">
      <div class="gva-btn-list">
        <el-button type="primary" icon="plus" @click="addUnit">新增单位</el-button>
      </div>
      <div class="ant-alert-info">
        <el-popover placement="left-start" :width="350" trigger="click" transition='el-zoom-in-left'>
          <div class="pop-content">
            <div class="pop-title">自定义列</div>
            <div class="check-list">
              <el-checkbox-group v-model="checkedColumns" @change="handleColumnsChange">
                <el-checkbox v-for="column in columns" :value="column" :label="column"></el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
          <template #reference>
            <div class="anticon">
              <el-icon size="16" color="#1890ff">
                <Setting />
              </el-icon>
              <div style="margin-left: 2px;">自定义列</div>
            </div>
          </template>
        </el-popover>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column align="left" label="单位名称" prop="name" v-if="checkedColumns.includes('单位名称')"></el-table-column>
        <el-table-column align="left" label="行政区划" v-if="checkedColumns.includes('行政区划')">
          <template #default="scope">
            <span>{{ scope.row.province + scope.row.city + scope.row.district + scope.row.town }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" label="单位地址" prop="address" v-if="checkedColumns.includes('单位地址')"></el-table-column>
        <el-table-column align="left" label="职级" prop="rank" v-if="checkedColumns.includes('职级')">
          <template #default="scope">
            <span>{{ getZj(scope.row.rank) }}</span>
          </template>
        </el-table-column>
        <el-table-column align="left" fixed="right" label="操作" min-width="160" v-if="checkedColumns.includes('操作')">
          <template #default="scope">
            <el-button type="primary" link icon="plus" @click="addUnit(scope.row)">
              新增下级单位
            </el-button>
            <el-button type="primary" link icon="plus" @click="addUser(scope.row)">
              新增用户
            </el-button>
            <el-button type="primary" link icon="edit" @click="editUnit(scope.row)">
              编辑
            </el-button>
            <el-button type="danger" link icon="delete" @click="delUnit(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination v-model:current-page="page" :page-size="pageSize" :total="total" layout="prev, pager, next"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <el-drawer v-model="dialogFormVisible" :size="appStore.drawerSize" :before-close="handleClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">{{ dialogTitle }}</span>
          <div>
            <el-button @click="closeDialog"> 取 消 </el-button>
            <el-button type="primary" @click="enterDialog"> 确 定 </el-button>
          </div>
        </div>
      </template>
      <el-form v-if="dialogFormVisible" ref="unitForm" label-width="150" :model="form" :rules="rules">
        <!-- <el-form-item label="上级单位" prop="name">
          <el-input v-model="form.parentName" disabled/>
        </el-form-item> -->
        <el-form-item label="单位名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="统一社会信用代码">
          <el-input v-model="form.organizationCode" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="行政区划" prop="province">
          <el-cascader ref="cascader" style="width: 100%" :options="areaList" :props="props1" v-model="pids" @change="areaChange" />
        </el-form-item>
        <el-form-item label="单位性质" prop="nature">
          <el-select v-model="form.nature" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in xzList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位类别" prop="unitType">
          <el-select v-model.number="form.unitType" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in lbList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位职级" prop="rank">
          <el-select v-model="form.rank" placeholder="请选择" style="width: 100%">
            <el-option v-for="item in zjList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位负责人" prop="leader">
          <el-input v-model="form.leader" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input v-model="form.address" placeholder="请输入" />
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer v-model="userVisible" :size="appStore.drawerSize" :before-close="handleUserClose" :show-close="false">
      <template #header>
        <div class="flex justify-between items-center">
          <span class="text-lg">新增用户</span>
          <div>
            <el-button @click="closeUserDialog"> 取 消 </el-button>
            <el-button type="primary" @click="enterUserDialog"> 确 定 </el-button>
          </div>
        </div>
      </template>
      <el-form v-if="userVisible" ref="userForms" label-width="100" :model="userForm" :rules="userRules">
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="账号" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密码" v-if="isEdit">
              <el-input v-model="userForm.password" disabled placeholder="请输入" />
            </el-form-item>
            <el-form-item label="密码" prop="password" v-else>
              <el-input v-model="userForm.password" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="角色" prop="roleId">
              <el-select v-model="userForm.roleId" placeholder="请选择" style="width: 100%">
                <el-option v-for="item in roleList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="单位" prop="unitId">
              <el-input v-model="userForm.unitName" disabled placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="姓名">
              <el-input v-model="userForm.name" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系方式">
              <el-input v-model="userForm.mobile" placeholder="请输入" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row class="w-full">
          <el-col :span="12">
            <el-form-item label="头像">
              <el-upload v-model:file-list="fileList" :action="adminUrl" :on-success="uploadSuccess"
                :headers="headerOdj" list-type="picture-card">
                <el-icon>
                  <Plus />
                </el-icon>
                <template #file="{ file }">
                  <div>
                    <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                    <span class="el-upload-list__item-actions">
                      <span class="el-upload-list__item-delete" @click="handleRemove(file)">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </span>
                    </span>
                  </div>
                </template>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-drawer>
  </div>
</template>
<script setup>
import {
  getDyList,
  getZjList
} from '@/api/xitongpeizhi'
import {
  getUnitList,
  deleteUnit,
  createUnit,
  updateUnit,
  getRegionList
} from '@/api/unit'
import {
  getAuthorityList
} from '@/api/authority'
import {
  createUser,
  editUser
} from '@/api/user'
import { reactive, ref, onMounted } from 'vue'
import { useAppStore } from "@/pinia";
import { useUserStore } from '@/pinia/modules/user'
import { ElMessage, ElMessageBox } from 'element-plus'
defineOptions({
  name: 'Unit'
})
const appStore = useAppStore()
const defaultProps = {
  children: 'children',
  label: 'name',
}

const xzList = ref([])
const lbList = ref([])
const zjList = ref([])

const form = ref({
  parentId:0,
  parentName:'',
  unitType:'',
  nature: '',
  rank: '',
  leader: '',
  address: '',
  sort: '',
  province: '',
  city: '',
  district: '',
  town: '',
  name: '',
  organizationCode: '',
  regionId:''
})

const searchInfo = ref({
  province: '',
  city: '',
  district: '',
  town: '',
  regionId:''
})

const userStore = useUserStore()
const headerOdj = ref({ token: userStore.token })
const adminUrl = ref('')
adminUrl.value = import.meta.env.VITE_BASE_PATH + '/file/upload'
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const dialogFormVisible = ref(false)
const userVisible = ref(false)
const rules = reactive({
  name: [{ required: true, message: '请输入单位名称', trigger: 'blur' }],
  address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }],
  leader: [{ required: true, message: '请输入单位负责人', trigger: 'blur' }],
  nature: [{ required: true, message: '请选择单位性质', trigger: 'change' }],
  rank: [{ required: true, message: '请选择单位职级', trigger: 'change' }],
  province: [{ required: true, message: '请选择行政区划', trigger: 'change' }],
})
const userRules = reactive({
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: true, message: '请输入密码', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色', trigger: 'change' }],
  unitId: [{ required: true, message: '请选择单位', trigger: 'change' }]
})
const unitForm = ref(null)
const userForms = ref(null)
const pids = ref([])
const props1 = {
  checkStrictly: true,
  label: 'name',
  value: 'name'
}
const props2 = {
  checkStrictly: true,
  label: 'name',
  value: 'id'
}
const initForm = () => {
  unitForm.value.resetFields()
  form.value = {
    parentId:0,
    parentName:'',
    nature: '',
    rank: '',
    leader: '',
    address: '',
    sort: '',
    province: '',
    city: '',
    district: '',
    town: '',
    name: '',
    organizationCode: '',
    regionId:''
  }
  pids.value = []
}
const userForm = ref({
  username: '',
  password: '',
  name: '',
  mobile: '',
  roleId: '',
  unitId: '',
  personalSignature: '',
  unitName: ''
})
const initUserForm = () => {
  userForms.value.resetFields()
  userForm.value = {
    username: '',
    password: '',
    name: '',
    mobile: '',
    roleId: '',
    unitId: '',
    personalSignature: '',
    unitName: ''
  }
  fileList.value = []
  pids.value = []
}
const checkedColumns = ref(['单位名称', '行政区划', '单位地址', '职级','操作'])

if (localStorage.getItem('columnData') && JSON.parse(localStorage.getItem('columnData')).unit) {
  checkedColumns.value = JSON.parse(localStorage.getItem('columnData')).unit
}
const columns = ref(['单位名称', '行政区划', '单位地址', '职级','操作'])
const handleColumnsChange = (val) => {
  let obj = {
    
  }
  if (localStorage.getItem('columnData')) {
    obj = JSON.parse(localStorage.getItem('columnData'))
  }
  obj.unit=val
  localStorage.setItem('columnData', JSON.stringify(obj))
}
const isEdit = ref(false)
const dialogTitle = ref('新增单位')
const addUnit = (row) => {
  if(row){
    form.value.parentId = row.id
    form.value.parentName = row.name
  }
  dialogTitle.value = '新增单位'
  isEdit.value = false
  dialogFormVisible.value = true
}
const closeDialog = () => {
  initForm()
  dialogFormVisible.value = false
}
const closeUserDialog = () => {
  initUserForm()
  userVisible.value = false
}
const handleClose = (done) => {
  initForm()
  done()
}
const handleUserClose = (done) => {
  initUserForm()
  done()
}
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}
const tableData = ref([])
// 查询
const getTableData = async () => {
  const res = await getUnitList({
    pageNumber: page.value,
    pageSize: pageSize.value,
    ...searchInfo.value
  })
  if (res.code == 200) {
    tableData.value = res.result
    total.value = res.result.length
  }
}
getTableData()
const areaList = ref([])
const roleList = ref([])
onMounted(() => {
  getRegionList().then(res => {
    areaList.value = res.result
  })
  getAuthorityList().then(res => {
    roleList.value = res.result
  })
  getDyList({pageNumber:1,pageSize:100}).then(res=>{
    xzList.value = res.result.data.filter(item=>item.type==1)
    lbList.value = res.result.data.filter(item=>item.type==2)
  })
  getZjList({pageNumber:1,pageSize:100}).then(res=>{
    zjList.value=res.result.data
  })
})
const enterDialog = async () => {
  unitForm.value.validate(async (valid) => {
    if (valid) {
      let res
      if (isEdit.value) {
        res = await updateUnit(form.value)
      } else {
        res = await createUnit(form.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initForm()
      dialogFormVisible.value = false
    }
  })
}
const enterUserDialog = async () => {
  userForms.value.validate(async (valid) => {
    if (valid) {
      let res
      if (isEdit.value) {
        res = await editUser(userForm.value)
      } else {
        res = await createUser(userForm.value)
      }
      if (res.code == 200) {
        ElMessage({
          type: 'success',
          message: isEdit.value ? '编辑成功' : '添加成功!'
        })
        getTableData()
      }
      initUserForm()
      userVisible.value = false
    }
  })
}
const delUnit = (row) => {
  ElMessageBox.confirm(
    '确认删除?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    const res = await deleteUnit(row.id)
    if (res.code === 200) {
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      getTableData()
    }
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '已取消删除'
    })
  })
}

const editUnit = async (row) => {
  form.value.parentId = row.id
  isEdit.value = true
  dialogTitle.value = '编辑单位'
  form.value = JSON.parse(JSON.stringify(row))
  if (row.province) {
    pids.value.push(row.province)
  }
  if (row.city) {
    pids.value.push(row.city)
  }
  // if (row.district) {
  //   pids.value.push(row.district)
  // }
  // if (row.town) {
  //   pids.value.push(row.town)
  // }
  form.value.unitId = form.value.id
  dialogFormVisible.value = true
}
const cascader = ref(null)
const areaChange = (val) => {
  let names = cascader.value.getCheckedNodes()[0].pathLabels
  if (names.length == 1) {
    form.value.province = names[0]
  } else if (names.length == 2) {
    form.value.province = names[0]
    form.value.city = names[1]
  } else if (names.length == 3) {
    form.value.province = names[0]
    form.value.city = names[1]
    form.value.district = names[2]
  } else {
    form.value.province = names[0]
    form.value.city = names[1]
    form.value.district = names[2]
    form.value.town = names[3]
  }
  form.value.regionId = cascader.value.getCheckedNodes()[0].data.id
}
const searchAreaChange = (val) => {
  searchInfo.value.regionId = val[val.length-1]
  // if (val.length == 1) {
  //   searchInfo.value.province = val[0]
  // } else if (val.length == 2) {
  //   searchInfo.value.province = val[0]
  //   searchInfo.value.city = val[1]
  // } else if (val.length == 3) {
  //   searchInfo.value.province = val[0]
  //   searchInfo.value.city = val[1]
  //   searchInfo.value.district = val[2]
  // } else {
  //   searchInfo.value.province = val[0]
  //   searchInfo.value.city = val[1]
  //   searchInfo.value.district = val[2]
  //   searchInfo.value.town = val[3]
  // }
}
const onSubmit = () => {
    page.value = 1
    getTableData()
}

const searchPids = ref([])
const onReset = () => {
  searchInfo.value = {
    province: '',
    city: '',
    district: '',
    town: '',
    regionId:''
  }
  searchPids.value = []
  getTableData()
}
const addUser = (row) => {
  userForm.value.unitId = row.id
  userForm.value.unitName = row.name
  userVisible.value = true
}

const fileList = ref([])
const handleRemove = (file) => {
  fileList.value = []
  userForm.value.personalSignature = ''
}
const uploadSuccess = (res) => {
  if (res.code != 200) {
    ElMessage({
      type: 'error',
      message: '上传失败' + res.msg
    })
    fileList.value.pop()
    return
  }
  userForm.value.personalSignature = res.result
}
function getZj(rank){
  let res = ''
  let obj = zjList.value.find(item=>item.id==rank)
  if(obj){
    res = obj.name
  }
  return res
}
</script>

<style lang="scss">
.flex {
  .area {
    flex: 2;
    background-color: #fff;
    margin: 0.5rem 20px 0.5rem 0;
  }

  .unit {
    flex: 4;
  }
}
.ant-alert-info {
  display: flex;
  justify-content: end;
  align-items: center;
  background-color: #e6f7ff;
  border: 1px solid #91d5ff;
  color: #1890ff;
  padding: 5px;

  .anticon {
    display: flex;
    align-items: center;
    cursor: pointer;
  }
}

.pop-content {
  .pop-title {
    font-weight: bold;
    padding-bottom: 4px;
    border-bottom: 1px solid rgba(5, 5, 5, 0.06);
  }

  .el-checkbox-group {
    font-size: 0;
    line-height: 0;
    display: flex;
    flex-wrap: wrap;
  }
}
</style>
